package com.xieyong.mywebsite.controller;

import com.github.pagehelper.PageInfo;
import com.xieyong.mywebsite.model.dto.Result;
import com.xieyong.mywebsite.model.entity.Article;
import com.xieyong.mywebsite.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @PostMapping()
    public Result<Article> add(@RequestBody @Validated(Article.Add.class) Article article) {
        articleService.add(article);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Article> delete(@PathVariable Integer id) {
        articleService.delete(id);
        return Result.success();
    }

    @PutMapping()
    public Result<Article> update(@RequestBody @Validated(Article.Update.class) Article article) {
        articleService.update(article);
        return Result.success();
    }

    @GetMapping("/detail")
    public Result<Article> detail(@RequestBody Integer id) {
        Article article = articleService.detail(id);
        return Result.success(article);
    }

    @GetMapping()
    public Result<List<Article>> list() {
        List<Article> articles = articleService.list();
        return Result.success(articles);
    }

    @GetMapping("/page")
    public Result<PageInfo<Article>> page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime,
            Article article){
        PageInfo<Article> articles = articleService.findByCondition(pageNum,pageSize,startTime,endTime,article);
        return Result.success(articles);
    }
}
